<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Components\Tools;
use App\Models\UserModels\Xunpan;
use App\Models\VoidsModels\CommentKey;

/**
 * 获取抖音询盘
 */
class DyXunpan extends Command {

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'DyXunpan';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '获取抖音询盘';
    protected $thirsdUrlMe = "http://139.186.147.106:5000/comment"; //自用的服务器评论接口地址
    protected $thirsdUrl = "http://api.xstatus.cn/douyin/video/comments?token=3440488a80744d30abe1a41f3a7062d5&aweme_id="; //第三方评论接口

    /**
     * Execute the console command.
     *
     * @return mixed
     */

    public function handle() {
        set_time_limit(0);
        Tools::commandsLog('DyXunpan_Begin:' . date("Y-m-d H:i:s"));
        $this->getXunpan();
        Tools::commandsLog('DyXunpan_End:' . date("Y-m-d H:i:s"));
    }

    /**
     *    询盘定时任务
     *    dataList			包含（关键词id，会员id，关键词名，询盘套餐总次数，套餐起始时间）
     *    numAll            询盘套餐的总数
     *    countAll       	会员总共得到的询盘数
     *    dayList           会员当天得到的询盘 评论的id 集合 array
     *    commentIds        会员当天得到的询盘 评论的id 集合 string
     *    countDay        	会员当天得到的询盘数
     *    countKey       	会员添加的可用关键次总数
     *    xun_number        当日可得到的询盘上限数
     *    nowCount       	当前可用的询盘数
     *    numOneKey       	每个关键词每天 每次 平均多少条
     */
    function getXunpan() {
     $xunpan = new Xunpan();

        $first = Tools::getOneconfig('/config/inquiry.json', ['first', 'xun_number']) ? Tools::getOneconfig('/config/inquiry.json', ['first', 'xun_number']) : 20;
        $middle = Tools::getOneconfig('/config/inquiry.json', ['middle', 'xun_number']) ? Tools::getOneconfig('/config/inquiry.json', ['middle', 'xun_number']) : 40;
        $tall = Tools::getOneconfig('/config/inquiry.json', ['tall', 'xun_number']) ? Tools::getOneconfig('/config/inquiry.json', ['tall', 'xun_number']) : 60;

        //查询可用的会员开通套餐未到时的可用的关键词询盘次数
        $dataList = $xunpan->selectKeyAll();
        // echo "<pre/>";print_r($dataList);exit;
        if ($dataList) {
            foreach ($dataList as $k => $v) {
                $numAll = $v['num2'];

                //会员总共得到的询盘数
                $count_comment = $xunpan->getCommentsum($v['user_id']);
                $countAll = $xunpan->commentAllCount($v['user_id']);
                $countAll = $countAll + $count_comment;

                //会员当天得到的询盘 评论的id  集合
                $dayList = $xunpan->commentDayList($v['user_id']);
                $commentIds = '';
                if ($dayList) {
                    foreach ($dayList as $ka => $va) {
                        $commentIds .= $va['comment_id'] . ",";
                    }
                    $commentIds = substr($commentIds, 0, -1);
                }
                //会员当天得到的询盘数
                $countDay = $dayList ? count($dayList) : 0;

                //会员添加的可用关键次总数
                $countKey = $xunpan->userKeyCount($v['user_id']);

                $xun_number = $v['meal_name'] == 'first' ? $first : ($v['meal_name'] == 'middle' ? $middle : $tall);//每日询盘上限数
                $nowCount = ($xun_number - $countDay) > 0 ? ($xun_number - $countDay) : 0;//当前可用的询盘数
                if($countKey>0){//新增判断 如果关键词数量大于0才分配 没有设置关键词不分配数据
					$numOneKey = $nowCount > ceil($xun_number / 4 / $countKey) ? ceil($xun_number / 4 / $countKey) : $nowCount;//当前关键词应被分配的询盘数
                }
                //如果已经得到的询盘总数小于套餐的询盘总数 并且 当前可得的询盘数大于0
                if ($countAll < $numAll && $numOneKey) {
                    $this->keyDistribution($v['user_id'], $v['id'], $v['name'], $commentIds, $numOneKey, $nowCount, $v['meal_name']);
                } else {
                    unset($dataList[$k]);
                }
				sleep(10);
            }
        }
        // echo "<pre/>";print_r($dataList);exit;
    }



    /**
      /**
     *    每一个关键词的评论分配
     *    user_id		用户id
     *    keyword_id    关键词id
     *    name        	关键词名称
     *    commentIds    当天已经得到的评论id集合
     *    numOneKey    	当前关键词可得到评论数
     *    nowCount    	当前可用的询盘数
     */ 
    function keyDistribution($user_id, $keyword_id, $name, $commentIds, $numOneKey, $nowCount, $meal_name)
    {
        $xunpan = new Xunpan();
        $contentLike = $xunpan->getKeyComment($user_id);

        //查询出可用的包含标题关键词、内容关键词的评论
		if($contentLike){
			$newCommentAll = $xunpan->newCommentAll($contentLike, $name, $commentIds);
		}
        
        if (!empty($newCommentAll)) {
            //先不分配了
            //$this->dataComment($newCommentAll, $user_id, $keyword_id, $numOneKey, $nowCount);
        } else {
            //走接口查找标题关键词的视频抓取评论
            //$url = $_SERVER['HTTP_HOST'] . "/xunpan/search";
            $url = "http://admin.weilaiyinsu.com/xunpan/search";  //线上地址
            //$url = "https://admin.91biopay.com/xunpan/search"; //测试环境地址
	    $this->postJson($url,['key'=>$name,'user_id'=>$user_id,'meal_name'=>$meal_name]);
             
                       // $this->searchVideo($name,$user_id,$meal_name);
		}
    }

    /**
     *    随机分配指定数评论给当前关键词
     *    dataList			条件查询出的当天的评论数据
     *    user_id        	用户编号
     *    keyword_id		用户关键词编号
     *    num				当前关键词分配的评论数
     *    nowCount			当前可用的询盘数
     */
    function dataComment($dataList, $user_id, $keyword_id, $num, $nowCount)
    {
        $data = [];
        $i = 0;
        if ($dataList && count($dataList) > $num && $num > 0) {
            $arr = array_rand($dataList, $num);
            if (is_array($arr)) {
                foreach ($arr as $k => $v) {
                    $data[$i]['partner_id'] = $user_id;
                    $data[$i]['keyword_id'] = $keyword_id;
                    $data[$i]['comment_id'] = $dataList[$v]['id'];
                    $data[$i]['create_time'] = date('Y-m-d', time());
                    ++$i;
                }
            } else {
                $data[$i]['partner_id'] = $user_id;
                $data[$i]['keyword_id'] = $keyword_id;
                $data[$i]['comment_id'] = $dataList[$arr]['id'];
                $data[$i]['create_time'] = date('Y-m-d', time());
            }
        } elseif ($dataList && count($dataList) <= $num && $num > 0) {
            foreach ($dataList as $k => $v) {
                $data[$i]['partner_id'] = $user_id;
                $data[$i]['keyword_id'] = $keyword_id;
                $data[$i]['comment_id'] = $v['id'];
                $data[$i]['create_time'] = date('Y-m-d', time());
                ++$i;
            }
        }
        $this->saveData($data, $nowCount);
        // echo "<pre/>";print_r($dataList);
        // echo "<pre/>";print_r($data);exit;
    }

    /**
     *    插入数据到会员询盘表
     *    data        需要插入到询盘数据的评论id、会员id、关键词id、当前日期集合
     *    nowCount    当前可用的询盘数
     */
    function saveData($data, $nowCount)
    {
        $xunpan = new Xunpan();
        if (isset($data[0])) {
            foreach ($data as $k => $v) {
                if (--$nowCount >= 0) {
                    $xunpan->saveComment($v);
                }
            }
        }
    }
	
	
	
	
	
	
	
	//检查需要查询的date数组
	function findAw($string){
		$string=json_decode($string,true);
		if(isset($string['data']) && !empty($string['data']) && is_array($string['data'])){
			$aweme_list=[];
			foreach($string['data'] as $k=>$v){
				$retunList=$this->forArr($v);
				if($retunList){
					$aweme_list[]=$retunList;
				}
			}
			return $aweme_list;
		}
		return false;
	}
	//循环查找数组里是否存在指定键 - 值
	function forArr($array){
		if (!is_array($array)) return null;
		if (isset($array['aweme_list'])) return $array['aweme_list'];
		if (isset($array['aweme_info'])) return $array['aweme_info'];
		foreach ($array as $item) {
			$return = $this->forArr($item);
			if (!is_null($return)) {
				return $return;
			}
		}  
		return null;
	}
	/**
	*	查找相关的关键词视频
	*	key			关键词
	*	meal_name：first(1)	middle(2)	tall(4)
	*/
	function searchVideo($key,$user_id,$meal_name){
		set_time_limit(0);
		$offsetCount=0;
                $offset = 10;
		if($meal_name=='tall'){
			$offsetCount=4;
		}elseif($meal_name=='middle'){
			$offsetCount=2;
		}                
                
		$url="http://139.186.147.106:5000/search?keyword={$key}&offset={$offset}";
		$data=$this->getWhileJson($url);
                //Tools::commandsLog('data:'.  json_encode($data));
		
	    if($data['datatype'] == 1){ //走旧版本
                        if(!empty($data['data']['data'][0])){
                                foreach($data['data']['data'] as $k=>$v){
//                                    echo '<pre>';
//                                    print_r($v);exit();
                                        if(!empty($v['aweme_info']['aweme_id'])){
                                                // echo $v['aweme_info']['aweme_id']."\r\n".$v['aweme_info']['desc']."\r\n".$key."\r\n\r\n\r\n";
                                                $this->urlGetCommentMe($v['aweme_info']['aweme_id'],0,$v['aweme_info']['desc'],$key,$user_id);
                                        }
                                }
                        }                    
                }else{  //走新版本
                
		//获取视频数据
		$data=str_replace(array("\r\n", "\r", "\n"),"---yks2021---",$data['data']);
		$data=explode("---yks2021---",$data);
		$aweme_list=[];

		foreach($data as $k=>$v){
			$index=strpos($v,'{"status_code":0,');
			if($index!==0){
				unset($data[$k]);
			}else{
				$returnArr=$this->findAw($v);
				if($returnArr && !empty($returnArr) && is_array($returnArr)){
					foreach($returnArr as $ka=>$va){
						if(!isset($va['aweme_id'])){
							foreach($va as $vv){
								unset($vv['rawdata']);
								$aweme_list[]=$vv;
							}
						}else{
							unset($va['rawdata']);
							$aweme_list[]=$va;
						}
					}
				}
			}
		}
//		 echo "<pre/>";print_r(($aweme_list));exit;
		//抓取评论
		if(!empty($aweme_list)){
			foreach($aweme_list as $item){
				$title=isset($item['desc']) ? $item['desc'] : $key;
				$this->urlGetCommentMe($item['aweme_id'],0,$title,$key,$user_id);
			}
		}
		
              }
              
	      //下一页
		$offsetCount=$offsetCount-1;
		if($offsetCount > 0){
			$offset=$offset+10;
			$this->morSearchVideo($key,$user_id,$offsetCount,$offset);
		}              
	}
	//自用视频评论抓取接口
	function urlGetCommentMe($videoId,$cursor,$title,$keyword,$user_id){
		$url=$this->thirsdUrlMe."?aweme_id={$videoId}&cursor={$cursor}&count=20";
		$data=$this->getWhileJson($url);
		if( isset($data['status']) && $data['status']=='success' && isset($data['code']) && $data['code']==200 && !empty($data['data']['comments'][0]) ){
			
			$this->videoCommentList($data['data']['comments'],$title,$keyword,$user_id);
			
			//下一页
			if( isset($data['data']['has_more']) && $data['data']['has_more']>0 ){
				$cursor=$cursor+20;
				$this->urlGetCommentMe($videoId,$cursor,$title,$keyword,$user_id);
			}
		}else{
			//接口错误入库
			$errorMsgData=[
				'type'=>0,
				'create_time'=>date('Y-m-d H:i:s'),
				'url'=>$url,
				'method'=>"get",
				'return'=>json_encode($data),
			];
			$errorMsg=new Douyin();
			$errorMsg->api_msg($errorMsgData);
		}
	}
        
	
	// 外网第三方 api 接口 获取一级评论信息根据需要取出数据 入库
	function urlGetComment($videoId,$cursor,$title,$keyword,$user_id){
		$url=$this->thirsdUrl."{$videoId}&cursor={$cursor}";
		$data=$this->getWhileJson($url,'');
		if(isset($data['status_code']) && $data['status_code']==0 && isset($data['x-status']) && $data['x-status'] && !empty($data['comments'][0]) ){
			
			$this->videoCommentList($data['comments'],$title,$keyword,$user_id);
			
			
			if(isset($data['has_more']) && $data['has_more']>0 ){
				$cursor=$cursor+20;//分页的？+20大概是因为一次只有20个数据 下一轮继续查询？
				$this->urlGetComment($videoId,$cursor,$title,$keyword,$user_id);
			}
		}
	}
	//存入评论
	function videoCommentList($commentList,$title,$keyword,$user_id){
		$CommentKey=new CommentKey();
		foreach($commentList as $k=>$v){
			$text=isset($v['text']) ? $v['text'] : '';
			$signature=isset($v['user']['signature']) ? $v['user']['signature'] : '';
			$video_id=isset($v['aweme_id']) ? $v['aweme_id'] : '';		//视频id
			$comment_id=isset($v['cid']) ? $v['cid'] : '';				//评论id
			$rec_comment=isset($v['reply_comment_total']) ? intval($v['reply_comment_total']) : 0;		//回复数
			
			$findIn=$this->findk($text,$signature,$user_id);
			$data=array(
				'nickname'=>isset($v['user']['nickname']) ? htmlspecialchars($v['user']['nickname'],ENT_QUOTES) : '',
				'signature'=>htmlspecialchars($signature,ENT_QUOTES),
				'user_id'=>isset($v['user']['unique_id']) && !empty($v['user']['unique_id']) ? $v['user']['unique_id'] : ( isset($v['user']['short_id']) ? $v['user']['short_id'] : ''),
				'sec_uid'=>isset($v['user']['sec_uid']) ? $v['user']['sec_uid'] : '',
				'content'=>htmlspecialchars($text,ENT_QUOTES),
				'create_time'=>date('Y-m-d H:i:s',$v['create_time']),
				'update_time'=>date('Y-m-d H:i:s',time()),
				'pt_type'=>1,
				'userImg'=>isset($v['user']['avatar_medium']['url_list'][1]) ? $v['user']['avatar_medium']['url_list'][1] : $v['user']['avatar_medium']['url_list'][0],
				'video_url'=>isset($v['aweme_id']) ? "https://www.douyin.com/video/".$video_id : '',
				'birthday'=>isset($v['user']['birthday']) ? $v['user']['birthday'] : '',
				'rec_comment'=>$rec_comment,
				'digg_count'=>isset($v['digg_count']) ? intval($v['digg_count']) : 0,
				'title'=>htmlspecialchars($title,ENT_QUOTES),
				'keyword'=>htmlspecialchars($keyword,ENT_QUOTES),
				'tells'=>substr($findIn,5) ? substr($findIn,5) : '',
				'uid'=>isset($v['user']['uid']) ? $v['user']['uid'] : '',
			);
			if($findIn){
				$CommentKey->saveVideoComment($data,$video_id,$comment_id,$keyword);
			}
		}
	}
	
	//查找是否存在需要的关键词 wx qq 电话号码
	function findk($text,$signature,$user_id){
		$re=$this->findkeyword($text,$user_id);
		if($re){
			$tells="tells";
			preg_match_all("/[a-z0-9_-]{6,20}/i",$signature,$signatureArr);
			if(isset($signatureArr[0][0])){
				$tells.=implode("\r\n",$signatureArr[0]);
			}
			return $tells;
		}
		return false;
	}
	//查找是否存在关键词
	function findkeyword($text,$user_id){
		/* $url=str_replace("/public",'',$_SERVER['DOCUMENT_ROOT']);
		$keywords=json_decode(file_get_contents($url."/config/keywords.json"),true);
		
		if( !empty($text) && isset($keywords['keywords'][0]) ){
			foreach($keywords['keywords'] as $k=>$v){
				if(stristr($text,$v)){
					return $text;
				}
			}
		} */
		
		$CommentKey=new CommentKey();
		$list=$CommentKey->getKey($user_id);
		
		if( !empty($text) && $list){
			foreach($list as $k=>$v){
				if(stristr($text,$v['name'])){
					return $text;
				}
			}
		}
		return false;
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	/**
	*	获取评论 get 请求 重试机制
	*	checkTest	需要正确匹配存在的字符串 否则 开启重试
	*	$retry		重试retry-1次	默认3次
	*	sleep		休眠时间 秒
	*/
	function getWhileJson($url,$checkTest='"status": "success", "code": 200,',$retry=4,$sleep=20){
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL,$url);
		curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
		curl_setopt($ch, CURLOPT_TIMEOUT,60);//连接后等待时间
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 1);//连接前等待时间
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
		curl_setopt($ch, CURLOPT_HEADER, FALSE);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);//为true，则会跟踪爬取重定向页面，否则，不会跟踪重定向页面
		curl_setopt($ch, CURLOPT_ENCODING, "");//返回乱码处理
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //不验证证书下同
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
		
		$output = curl_exec($ch);
		
		if($checkTest){
			while( !strpos($output,$checkTest) && --$retry > 0 ){
				sleep($sleep);
				$output = curl_exec($ch);
			}
		}
		
		curl_close($ch);
		return json_decode($output, true);
	}
	
	//post请求
	function postJson($url, $data = array()){
		//初始化
		$curl = curl_init();
		//设置抓取的url
		curl_setopt($curl, CURLOPT_URL, $url);
		//设置头文件的信息作为数据流输出
		curl_setopt($curl, CURLOPT_HEADER, 0);
		//超时时间
		curl_setopt($curl, CURLOPT_TIMEOUT,1);
		curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);//连接前等待时间
		//设置获取的信息以文件流的形式返回，而不是直接输出。
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		//设置post方式提交
		curl_setopt($curl, CURLOPT_POST, 1);
		//设置post数据
		curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); //不验证证书下同
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
		curl_setopt($curl, CURLOPT_HTTPHEADER, array(
			'Content-Type: application/json',
			'Content-Length: ' . strlen(json_encode($data)))
		);

		//执行命令
		$json = curl_exec($curl);
		//关闭URL请求
		curl_close($curl);
		return json_decode($json, true);
	}
}
